/**
 * Created by Simon on 2017/4/11.
 */

var express = require('express');
var UUID = require('uuid');
var fs = require('fs');
var router = express.Router();
var multer = require('multer');
var certificationDao = require('../dao/aijiduo/certification-dao');
var Certification = require('../model/certification-model');
var vegetableDao = require('../dao/aijiduo/vegetable-dao');
var Vegetable = require('../model/vegetable-model');
var kingLandHomeDao = require('../dao/king-land/index-dao');
var KinglandBanner = require('../model/kingland-banner-model');
var fruitDao = require('../dao/aijiduo/fruit-dao');
var Fruit = require('../model/fruit-model');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    var currentDate = new Date();
    var year = currentDate.getFullYear();
    var month = currentDate.getMonth() + 1;
    var day = currentDate.getDate();
    var generatedPath = `upload/${year}-${month}-${day}/`;
    req.generatedPath = generatedPath;
    try {
      fs.mkdirSync(generatedPath, 511, function (err) {});
    } catch (e) {}
    console.log('create folder');
    cb(null, generatedPath);
  },
  filename: function (req, file, cb) {
    var fileName = UUID.v1() + '.png';
    req.generatedFileName = fileName;
    cb(null, fileName);
  }
});

var uploader = multer({storage: storage});

router.get('/certification', function (req, res) {
  certificationDao.getAllCertifications(function (certs) {
    var renderData = {
      certs: certs || []
    };
    res.render('./manage/manage-certification.ejs', renderData);
  });
});

router.get('/getCertificationById', function (req, res) {
  var id = req.param('id');
  certificationDao.getCertificationById(id, function (cert) {
    res.json(cert);
  });
});

router.post('/postCertification', uploader.single('logo'), function (req, res) {
  var imageUrl = '/' + req.generatedPath + req.generatedFileName;
  var cnName = req.param('cnName');
  var enName = req.param('enName');
  var spaName = req.param('spaName');
  var status = req.param('status') ? 1 : 0;
  var id = req.param('id');
  var certModel = new Certification(id, cnName, enName, spaName, new Date(), status, imageUrl);
  console.log('status', status);
  if(id) {
    certificationDao.getCertificationById(id, function (cert) {
      try {
        cert.imageUrl && fs.unlinkSync(cert.imageUrl.slice(1));
      } catch (e) {
        console.log('Error', e);
      }
      certificationDao.saveOrUpdate(certModel);
      res.redirect('/manage/certification');
    });
  } else {
    certificationDao.saveOrUpdate(certModel);
    res.redirect('/manage/certification');
  }
});

router.get('/deleteCertificationById', function (req, res) {
  var id = req.param('id');
  certificationDao.getCertificationById(id, function (cert) {
    try {
      cert.imageUrl && fs.unlinkSync(cert.imageUrl.slice(1));
    } catch (e) {
      console.log('Error', e);
    }
    certificationDao.deleteById(id, function () {
      res.json({
        id: id,
        success: true
      });
    });
  });
  
});

router.get('/vegetable', function (req, res) {
  vegetableDao.getAllVegetables(function (vegetables) {
    var renderData = {
      vegetables: vegetables || []
    };
    res.render('./manage/manage-vegetable.ejs', renderData);
  });
});

router.get('/getVegetableById', function (req, res) {
  var id = req.param('id');
  vegetableDao.getVegetableById(id, function (vegetable) {
    res.json(vegetable);
  });
});

router.post('/postVegetable', uploader.single('vegetablePicture'), function (req, res) {
  let imageUrl = '/' + req.generatedPath + req.generatedFileName;
  console.log('imageUrl', imageUrl);
  let cnName = req.param('cnName');
  let enName = req.param('enName');
  let spaName = req.param('spaName');
  let cnBrief = req.param('cnBrief');
  let enBrief = req.param('enBrief');
  let spaBrief = req.param('spaBrief');
  let cnMethod = req.param('cnMethod');
  let enMethod = req.param('enMethod');
  let spaMethod = req.param('spaMethod');
  let season = req.param('season');
  let type = req.param('type');
  let status = req.param('status') ? 1 : 0;
  let id = req.param('id');
  let vegetableModel = new Vegetable(id, cnName, enName, spaName, cnBrief, enBrief, spaBrief, cnMethod, enMethod, spaMethod, season, imageUrl, type, new Date());
  if(id) {
    vegetableDao.getVegetableById(id, function (vegetable) {
      try {
        vegetable.imageUrl && fs.unlinkSync(vegetable.imageUrl.slice(1));
      } catch (e) {
        console.log('customer Error', e);
      }
      vegetableDao.saveOrUpdate(vegetableModel);
      res.redirect('/manage/vegetable');
    });
  } else {
    vegetableDao.saveOrUpdate(vegetableModel);
    res.redirect('/manage/vegetable');
  }
});

router.get('/deleteVegetableById', function (req, res) {
  var id = req.param('id');
  vegetableDao.getVegetableById(id, function (cert) {
    try {
      cert.imageUrl && fs.unlinkSync(cert.imageUrl.slice(1));
    } catch (e) {
      console.log('customer Error', e);
    }
    vegetableDao.deleteById(id, function () {
      res.json({
        id: id,
        success: true
      });
    });
  });
  
});

router.get('/king-land/index', function (req, res) {
  kingLandHomeDao.getAllBanners(function (banners) {
    var renderData = {
      banners: banners || []
    };
    res.render("./manage/king-land/home.ejs", renderData);
  });
});
router.get(`/king-land/index/getBannerById`, function (req, res) {
  let id = req.param('id');
  kingLandHomeDao.getBannerById(id, function (banner) {
    var renderData = {
      banner: banner || {}
    };
    res.json(renderData);
  });
});

router.post('/king-land/index/postBanner', uploader.single('homeBanner'), function (req, res) {
  let imageUrl = '/' + req.generatedPath + req.generatedFileName;
  let name = req.param('name');
  let status = req.param('status') ? 1 : 0;
  let sortNumber = req.param('sortNumber');
  let id = req.param('id');
  let banner = new KinglandBanner(id, name, imageUrl, status, new Date(), sortNumber);
  if(id) {
    kingLandHomeDao.getBannerById(id, function (oldBanner) {
      try {
        oldBanner.imageUrl && fs.unlinkSync(oldBanner.imageUrl.slice(1));
      } catch (e) {
        console.log('customer Error', e);
      }
      kingLandHomeDao.saveOrUpdate(banner);
      res.redirect('/manage/king-land/index');
    });
  } else {
    kingLandHomeDao.saveOrUpdate(banner);
    res.redirect('/manage/king-land/index');
  }
});
router.get('/king-land/index/deleteBannerById', function (req, res) {
  let id = req.param('id');
  kingLandHomeDao.getBannerById(id, function (banner) {
    try {
      banner.imageUrl && fs.unlinkSync(banner.imageUrl.slice(1));
    } catch (e) {
      console.log('Error', e);
    }
    kingLandHomeDao.deleteById(id, function () {
      res.json({
        id: id,
        success: true
      });
    });
  });
});

router.get(`/aijiduo/fruit`, function (req, res) {
  fruitDao.getAllFruits(function (fruits) {
    var renderData = {
      fruits: fruits || []
    };
    res.render('./manage/manage-fruit.ejs', renderData);
  });
});
router.get(`/aijiduo/getFruitById`, function (req, res) {
  let id = req.param('id');
  fruitDao.getFruitById(id, function (fruit) {
    res.json(fruit);
  });
});
router.get(`/aijiduo/deleteFruitById`, function (req, res) {
  let id = req.param('id');
  fruitDao.getFruitById(id, function (banner) {
    try {
      banner.imageUrl && fs.unlinkSync(banner.imageUrl.slice(1));
    } catch (e) {
      console.log('delete image error', e);
    }
    fruitDao.deleteById(id, function () {
      res.json({
        id: id,
        success: true
      });
    });
  });
});
router.post(`/aijiduo/postFruit`,uploader.single('fruitPicture'), function (req, res) {
  let imageUrl = '/' + req.generatedPath + req.generatedFileName;
  let cnName = req.param('cnName');
  let enName = req.param('enName');
  let spaName = req.param('spaName');
  let cnBrief = req.param('cnBrief');
  let enBrief = req.param('enBrief');
  let spaBrief = req.param('spaBrief');
  let status = req.param('status') ? 1 : 0;
  let sortNumber = req.param('sortNumber');
  let id = req.param('id');
  let fruit = new Fruit(id, cnName, enName, spaName, status, cnBrief, enBrief, spaBrief, new Date(), imageUrl);
  if(id) {
    fruitDao.getFruitById(id, function (oldFruit) {
      try {
        oldFruit.imageUrl && fs.unlinkSync(oldFruit.imageUrl.slice(1));
      } catch (e) {
        console.log('customer Error', e);
      }
      fruitDao.saveOrUpdate(fruit, function () {
        res.redirect('/manage/aijiduo/fruit');
      });
    });
  } else {
    fruitDao.saveOrUpdate(fruit, function () {
      res.redirect('/manage/aijiduo/fruit');
    });
  }
});

module.exports = router;